package xyx.ysfwpt.controller;

import com.aliyuncs.exceptions.ClientException;
import io.swagger.annotations.*;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import xyx.ysfwpt.api.AliyunMessageServiceAPI;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/ysfwpt")
@Api(tags = {"阿里云接口"},description = "")
public class AliyunController {

    @ApiOperation(value = "发送短信验证码",notes = "根据手机收到的验证码重置用户密码")
    @ApiResponses(value = { @ApiResponse(code = 200, message = "发送成功")})
    @RequestMapping(value="/sendMessage",method=RequestMethod.POST)
    @ResponseBody
    public JSONObject sendMessage(@ApiParam(value = "联系方式",required = true) @RequestParam(value = "phonumber", required = true)String phonumber,
                                  HttpServletResponse response) {
        JSONObject jsonObject = new JSONObject();

        //随机生成六位随机数
        StringBuffer stringBuffer=new StringBuffer();
        for (int x = 0;x <= 5;x ++) {
            int random = (int)(Math.random() * (10 - 1));
            stringBuffer.append(random);
        }
        String string = stringBuffer.toString();
        int vcode = Integer.parseInt(string);

        //发送短信验证码
        AliyunMessageServiceAPI api = new AliyunMessageServiceAPI();
        try {
            String result = api.sendMessage(phonumber,vcode);
            if(result == "SUCCESS"){
                //将验证码加密后存入cookie
                String value = String.valueOf(vcode);
                byte[] base64 = Base64.encodeBase64(value.getBytes());
                String cookievalue = new String(base64);
                Cookie vcodeCookie = new Cookie("vcodeCookie",cookievalue);
                vcodeCookie.setMaxAge(5*60);
                response.addCookie(vcodeCookie);
//                jsonObject.put("vcode",vcode);
            }
            jsonObject.put("result",result);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
}